﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace WikiCsharpCommon
{
    public class WikiCsharpTags
    {
        private bool m_bAnchor = false;
        private Regex m_reRegExp = null;
        private string m_sReplacementString = "";

        public WikiCsharpTags(string sRegExp, string sReplacementString)
        {
            m_reRegExp = new Regex(sRegExp, RegexOptions.Multiline | RegexOptions.Compiled);
            m_sReplacementString = sReplacementString;
        }

        public WikiCsharpTags(string sRegExp, string sReplacementString, bool bAnchor)
        {
            m_reRegExp = new Regex(sRegExp, RegexOptions.Multiline | RegexOptions.Compiled);
            m_sReplacementString = sReplacementString;
            m_bAnchor = bAnchor;
        }

        public string ApplyTags(string currentText)
        {
            if (m_bAnchor)
                return ApplyTagsAddAnchor(currentText);

            return m_reRegExp.Replace(currentText, m_sReplacementString);
        }

        public string ApplyTagsAddAnchor(string currentText)
        {
            int increment = 1;

            return m_reRegExp.Replace(currentText, delegate(Match match)
                                {
                                    string tmp = string.Format(m_sReplacementString, increment);
                                    ++increment;
                                    for (int i = 0; i < match.Groups.Count; ++i)
                                    {
                                        tmp = tmp.Replace("$" + i.ToString(), match.Groups[i].Value);
                                        tmp = tmp.Replace("${" + i.ToString() + "}", match.Groups[i].Value);
                                    }

                                    return tmp;
                                });
        }
    }
}
